package com.macro.mall.controller;

import com.macro.mall.common.api.CommonResult;
import com.macro.mall.dto.CosUploadPolicyDto;
import com.macro.mall.dto.FileUploadDto;
import com.macro.mall.service.CosService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 腾讯云COS文件上传控制器
 * 
 * @author rhc
 * @date 2025-08-08
 */
@Controller
@Api(tags = "CosController")
@Tag(name = "CosController", description = "腾讯云COS文件上传管理")
@RequestMapping("/cos")
public class CosController {

    private static final Logger LOGGER = LoggerFactory.getLogger(CosController.class);

    @Autowired
    private CosService cosService;

    @ApiOperation("获取上传策略")
    @GetMapping("/policy")
    @ResponseBody
    public CommonResult<CosUploadPolicyDto> policy() {
        try {
            LOGGER.info("收到获取上传策略请求");

            // 对于直接上传模式，返回空的策略对象
            // 前端会使用 /cos/upload 接口进行上传
            CosUploadPolicyDto policyDto = new CosUploadPolicyDto();

            return CommonResult.success(policyDto);
        } catch (Exception e) {
            LOGGER.error("获取上传策略失败: {}", e.getMessage(), e);
            return CommonResult.failed("获取上传策略失败: " + e.getMessage());
        }
    }

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    @ResponseBody
    public CommonResult<FileUploadDto> upload(@RequestPart("file") MultipartFile file) {
        try {
            LOGGER.info("收到文件上传请求，使用腾讯云COS存储");

            if (file.isEmpty()) {
                return CommonResult.failed("文件不能为空");
            }

            // 使用COS服务进行文件上传
            FileUploadDto result = cosService.upload(file);
            LOGGER.info("文件上传成功，URL: {}", result.getUrl());

            return CommonResult.success(result);
        } catch (Exception e) {
            LOGGER.error("文件上传失败: {}", e.getMessage(), e);
            return CommonResult.failed("文件上传失败: " + e.getMessage());
        }
    }

    @ApiOperation("文件删除")
    @PostMapping("/delete")
    @ResponseBody
    public CommonResult<String> delete(@RequestParam("objectName") String objectName) {
        try {
            LOGGER.info("收到文件删除请求，使用腾讯云COS删除");

            boolean success = cosService.delete(objectName);
            if (success) {
                LOGGER.info("文件删除成功: {}", objectName);
                return CommonResult.success("文件删除成功");
            } else {
                return CommonResult.failed("文件删除失败");
            }
        } catch (Exception e) {
            LOGGER.error("文件删除失败: {}", e.getMessage(), e);
            return CommonResult.failed("文件删除失败: " + e.getMessage());
        }
    }
}